package com.sjtu.rest;

import com.sjtu.constants.ApiConstants;
import com.sjtu.form.JobInvokeForm;
import com.sjtu.form.JobResult;
import com.sjtu.spi.JobResultPushService;
import com.sjtu.spi.JobRunnable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

/**
 * nerine
 * 1/29/2020
 */
@Slf4j
@RestController
public class JobReceiveRest {
    @Autowired
    private ApplicationContext ctx;
    @Autowired
    private ThreadPoolTaskExecutor sjtuJobThread;
    @Autowired
    private JobResultPushService jobResultPushService;

    @PostMapping(ApiConstants.CLIENT_INVOKE_URL)
    public short receive(@Valid @RequestBody JobInvokeForm form) {
        try {
            JobRunnable job = ctx.getBean(form.getBeanName(), JobRunnable.class);
            if(job == null) {
                log.error(String.format("no job found: %s, sequenceId: %s", form.getBeanName(), form.getSequenceId()));
                return ApiConstants.NO_SERVICE_FOUND;
            }
            sjtuJobThread.execute(() -> {
                Date beginTime = new Date();
                JobResult jobResult;
                try {
                    jobResult = job.run();
                } catch (Exception e) {
                    log.error(String.format("job run exception: %s, sequenceId: %s", form.getBeanName(), form.getSequenceId()), e);
                    jobResult = JobResult.fail(e.getMessage());
                }
                jobResult.setBeginTime(beginTime);
                jobResult.setEndTime(new Date());
                jobResult.setSequenceId(form.getSequenceId());
                jobResult.setSystemId(form.getSystemId());
                jobResultPushService.push(jobResult, form.getBeanName());
            });
            return ApiConstants.SUCCESS;
        }catch (Exception e) {
            log.error(String.format("no job found: %s, sequenceId: %s", form.getBeanName(), form.getSequenceId()), e);
            return ApiConstants.FAIL;
        }
    }
}
